package com.ujiuye.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ujiuye.bean.ResultVO;
import com.ujiuye.bean.User;
import com.ujiuye.dao.UserDao;
import com.ujiuye.util.ToJsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ClassName: UserServlet <br/>
 * Description: <br/>
 * date: 2021/9/16 11:07<br/>
 *
 * @author 荒<br />
 * @since JDK 1.8
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {

    UserDao ud = new UserDao();

    /**
     * 登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //调用dao层
        User user = ud.login(username,password);

        //给出响应
        ResultVO vo = null;
        if(user != null) {
            vo = new ResultVO(200,"欢迎你来到图书管理系统",user);
        }else {
            vo = new ResultVO(500,"登陆失败，请重新登录",user);
        }
        //一json形式返回
        //方式一：
//        ObjectMapper om = new ObjectMapper();
//        String json = om.writeValueAsString(vo);
//        resp.getWriter().print(json);
        //方式二：
        String json = ToJsonUtils.toJson(vo);
        resp.getWriter().print(json);
    }
}
